<template>
  <a-tree-select
      v-model:value="value"
      style="width: 100%"
      show-search
      treeNodeFilterProp="name"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :tree-data="treeData"
      placeholder="请选择部门"
      tree-default-expand-all
      @change="handleChange"
  >
  </a-tree-select>
</template>

<script lang="ts">
import {defineComponent, toRefs, reactive} from 'vue'
import {TreeSelect} from 'ant-design-vue'
import {deptSelectDeplist} from '@/api/dept'

export default defineComponent({
  name: "select-department",
  components: {[TreeSelect.name]: TreeSelect},
  props: ['modelValue'],
  setup(props, {emit}) {
    const state = reactive({
      treeData: [] as any[],
      value: [props.modelValue]
    })

    const list2tree = (items: any[], parent: string | number): any[] => {
      return items.filter(item => item.parent == parent).map(item => ({
        ...item,
        title: item.name,
        key: item.departmentid,
        value: item.departmentid,
        children: list2tree(items, item.departmentid)
      }))
    }

    deptSelectDeplist({page: 1,limit: 100}).then(res => state.treeData = list2tree(res.data, 0))
    const handleChange = (value) => {
      emit('update:modelValue', value.toString())
    }

    return {
      ...toRefs(state),
      handleChange
    }
  }
})
</script>

<style scoped>
</style>
